package framework.mybatis.annotation1;

import framework.mybatis.annotation1.mapper.UserMapper;
import framework.mybatis.annotation1.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Reader;

/**
 * Mapper代理开发模式：（详见 https://blog.csdn.net/qq_32166627/article/details/70741729）
 * 1，mapper接口的全限定名要和 mapper映射文件的 namespace 相同。
 * 2，mapper接口的方法名称要和 mapper映射文件的 子标签（statement） 的 id相同。
 * 3，mapper接口的方法参数只能有一个，且类型要和 mapper映射文件中 statement 的 parameterType 保持一致。
 * 4，mapper接口的返回值类型要和 mapper映射文件中 statement 的 resultType或resultMap 中的type值保持一致
 *
 * @author ME
 * @date 2021/4/29
 */
public class AnnotationConfigTest1 {

    private static final Logger LOG = LoggerFactory.getLogger(AnnotationConfigTest1.class);

    private static SqlSessionFactory sqlSessionFactory;

    @Test
    public void test() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            User u1 = new User(999);
            mapper.delUser(u1);

            User user = new User(999, "Lucy", 14);
            int result = mapper.addUser(user);
            Assert.assertEquals("插入 1行", 1, result);
            LOG.info("insert User[999]: {}", mapper.getUser(user));
            LOG.info("UserVO: {}", mapper.getUserVO(user));

            user.setAge(17);
            result = mapper.updateUser(user);
            Assert.assertEquals("更新 1行", 1, result);
            LOG.info("update User[999]: {}", mapper.getUser(user));

            // 简单参数，需要用 @Param 指定属性名
            result = mapper.simpleUpdate(999, "Jack", 88);
            Assert.assertEquals("更新 1行", 1, result);
            LOG.info("simple param update: {}", mapper.getUserById(999));

            result = mapper.delUser(user);
            Assert.assertEquals("删除 1行", 1, result);
            LOG.info("delete User[999]: {}", mapper.getUser(user));
        }
    }

    static {
        try {
            Reader reader = Resources.getResourceAsReader("framework/mybatis/annotation1/config-annotation1.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
